/**
 * Object对象转JSON字符串
 * @param {Object} o
 * @returns {String}
 */
export function jsonToStr(o) {
    try {
        return JSON.stringify(o)
    } catch (e) {
        return ''
    }
}

/**
 * 转换为JSON对象
 * @param {String} str
 * @returns {Object}
 */
export function toJSON(str) {
    try {
        return JSON.parse(str)
    } catch (e) {
        return {}
    }
}

/**
 * Object格式化/粗暴克隆
 * @param {Object} o
 * @return {Object}
 */
export function fastClone(o) {
    try {
        return JSON.parse(JSON.stringify(o))
    } catch (e) {
        return {}
    }
}

/**
 * 深度克隆对象
 * @param {Object} target
 * @param {Object} form
 * @returns {Object}
 * @eg deepClone({},{})
 */
export function deepClone(/* target, form */) {
    const isObj = (o) => Object.prototype.toString.call(o) === '[object Object]'
    let target = arguments[0]
    const form = arguments[1]
    if (!isObj(target)) target = {}
    if (!isObj(form)) return target

    Object.keys(form).forEach(key => {
        // 防止对象原型被污染，防止永无休止的循环
        if (key === '__proto__') return
        const row = form[key]
        if (row === undefined) return
        if (isObj(row)) {
            target[key] = deepClone(target[key], row)
        } else if (Array.isArray(row)) {
            if (!Array.isArray(target[key])) target[key] = []
            row.forEach((col, index) => {
                if (isObj(col)) {
                    target[key][index] = deepClone(target[key][index], col)
                } else {
                    target[key][index] = col
                }
            })
        } else {
            target[key] = row
        }
    })

    return target
}
